//根据资源组名称查询资源组
data "alicloud_resource_manager_resource_groups" "rmrg" {
  name_regex = var.resource_group_name
}

//根据资源组id查询vpc
data "alicloud_vpcs" "vpcs2" {
  resource_group_id = data.alicloud_resource_manager_resource_groups.rmrg.groups.0.id
}

//根据资源组id查询vswitch
data "alicloud_vswitches" "vsws" {
  resource_group_id = data.alicloud_resource_manager_resource_groups.rmrg.groups.0.id
  zone_id           = var.availability_zone
}

//根据vpc id查询安全组
data "alicloud_security_groups" "sgs" {
  vpc_id     = data.alicloud_vpcs.vpcs2.vpcs.0.id
  name_regex = "^内部"
}

//创建密钥对
data "alicloud_ecs_key_pairs" "ekps" {
  name_regex        = var.key_name
  resource_group_id = data.alicloud_resource_manager_resource_groups.rmrg.groups.0.id
}

resource "alicloud_instance" "ecs_instance" {
  count                      = var.instance_number
  security_groups            = data.alicloud_security_groups.sgs.groups.*.id
  instance_type              = var.instance_type
  system_disk_category       = var.disk_category
  system_disk_size           = var.disk_size
  image_id                   = var.image_id
  instance_name              = var.instance_name
  vswitch_id                 = data.alicloud_vswitches.vsws.vswitches.0.id
  internet_max_bandwidth_out = 0
  key_name                   = var.instance_password == "" ? data.alicloud_ecs_key_pairs.ekps.key_pairs.0.id : ""
  resource_group_id          = data.alicloud_resource_manager_resource_groups.rmrg.groups.0.id
  password                   = var.instance_password
  tags = {
    application = var.tags_application
    owner       = var.tags_owner
  }
  volume_tags = {
    application = var.tags_application
    owner       = var.tags_owner
  }
}
